//
//  HomeVipCell.swift
//  HengYouCai
//
//  Created by lwj on 2018/3/28.
//  Copyright © 2018年 lwj. All rights reserved.
//

import UIKit

protocol VipCellDelegate {
    func jumpToDetailVC(currentItem : Int)
}

class HomeVipCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource {
   
    
   
//    func jumpToDetailVC(currentItem : Int) {
//        //
//    }
    var dataArr :Array<ProjectModel>!
    var pageControl : UIPageControl!
    var delegate : VipCellDelegate?
    var collectionView : UICollectionView!
//    var callBack : (Int) -> ()?
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeVipCollectionCellID", for: indexPath) as! HomeVipCollectionCell
        cell.configurationCellWithModel(dataArr[indexPath.row])
        return cell
    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        delegate?.jumpToDetailVC(currentItem: indexPath.item)
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
       
        let currentPage : Int = Int((scrollView.contentOffset.x + 180)/(180 + 15))
    
        if currentPage > dataArr.count {
            pageControl.currentPage = dataArr.count
        }else if currentPage < 0 {
            pageControl.currentPage = 0
        }else{
            pageControl.currentPage = currentPage
        }
       

//        print(scrollView.contentOffset)
    }
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        
        self.selectionStyle = .none
        self.backgroundColor = UIColor.white
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func setUpUIWithData(modelArr :Array<ProjectModel>){
        
        dataArr = modelArr
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 180, height: 160)
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 25
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: 162), collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.register(HomeVipCollectionCell.self, forCellWithReuseIdentifier: "HomeVipCollectionCellID")
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        self.addSubview(collectionView)
        pageControl = UIPageControl()
        pageControl.numberOfPages = dataArr.count
        pageControl.currentPage = 0
        pageControl.isEnabled = false
        pageControl.pageIndicatorTintColor = ColorFromRGBHex_WL(0xE6D9BD)
        pageControl.currentPageIndicatorTintColor = ColorFromRGBHex_WL(0xc1a159)
//        pageControl.addTarget(self, action: #selector(pageChange), for: .valueChanged)
        self.addSubview(pageControl)
        _ = pageControl.sd_layout()
            .leftSpaceToView(self,0)?
            .rightSpaceToView(self,0)?
            .bottomSpaceToView(self,10)?
            .heightIs(20)
    }
    

    
}

class HomeVipCollectionCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.layer.shadowColor = ColorFromRGBHex_WL(0xeeeeee).cgColor
        self.layer.shadowOpacity = 1
        self.layer.shadowOffset = CGSize(width: 0, height: 0)
//        self.clipsToBounds = true
        setupUI()
    }
    
    /// 标题
    var titleLab : UILabel!
    /// 历史年化
    var profitTextLab : UILabel!
    /// 标的 状态
    var statusImg : UIImageView!
    /// 历史年化收益率
    var profitLab : UILabel!
    /// 竖直的灰线
    var lineView : UIView!
    /// 投资期限
    var limitLab : UILabel!
    /// 剩余可投
    var surplusAmountLab : UILabel!
    /// 活动标签
    var tagsView : JCWActiveTagView!
    
    func setupUI() {
        
        let bgView = UIView()
        bgView.backgroundColor = UIColor.white
        self.contentView.addSubview(bgView)
        _ = bgView.sd_layout()
            .topSpaceToView(self.contentView,0)?
            .leftSpaceToView(self.contentView,0)?
            .rightSpaceToView(self.contentView,0)?
            .heightIs(160)
        //
        titleLab = UILabel()
        titleLab.font = Font_WL(15)
        titleLab.textAlignment = .center
        bgView.addSubview(titleLab)
        _ = self.titleLab.sd_layout()
            .topSpaceToView(bgView,4)?
            .leftSpaceToView(bgView,4)?
            .rightSpaceToView(bgView,4)?
            .heightIs(26)
        //
        statusImg = UIImageView()
        statusImg.center = CGPoint(x: self.width-16, y: 16)
        statusImg.bounds = CGRect(x: 0, y: 0, width: 44, height: 44)
        bgView.addSubview(statusImg)
        //
        profitTextLab = UILabel()
//        profitTextLab.text = "历史年化收益率"
        profitTextLab.font = Font_WL(11)
        profitTextLab.textAlignment = .center
        profitTextLab.textColor = Normal_666Color
        bgView.addSubview(profitTextLab)
        _ = self.profitTextLab.sd_layout()
            .topSpaceToView(titleLab,20)?
            .leftSpaceToView(bgView,0)?
            .rightSpaceToView(bgView,0)?
            .heightIs(11)
        //
        profitLab = UILabel()
        profitLab.textAlignment = .center
        profitLab.textColor = Normal_ThemeColor  //ColorFromRGBHex_WL(0xc1a057)
        profitLab.font = Font_WL(18)
        bgView.addSubview(profitLab)
        _ = self.profitLab.sd_layout()
            .topSpaceToView(profitTextLab,5)?
            .leftSpaceToView(bgView,0)?
            .rightSpaceToView(bgView,0)?
            .heightIs(18)
        //
        lineView = UIView()
        lineView.backgroundColor = ColorFromRGBHex_WL(0xeeeeee)
        bgView.addSubview(lineView)
        _ = self.lineView.sd_layout()
            .topSpaceToView(profitLab,20)?
            .widthIs(0.5)?
            .heightIs(12)?
            .centerXEqualToView(bgView)
        
        surplusAmountLab = UILabel()
        surplusAmountLab.textColor = Normal_333Color
        surplusAmountLab.font = Font_WL(12)
        surplusAmountLab.textAlignment = .center
        surplusAmountLab.backgroundColor = UIColor.clear
        bgView.addSubview(surplusAmountLab)
        _ = self.surplusAmountLab.sd_layout()
            .topEqualToView(lineView)?
            .bottomEqualToView(lineView)?
            .leftSpaceToView(bgView,0)?
            .rightSpaceToView(bgView,0)
        //
        tagsView = JCWActiveTagView(ColorFromRGBHex_WL(0xece2cd),false, "")
        bgView.addSubview(tagsView)

    }
    func configurationCellWithModel(_ vipModel: ProjectModel) {
        //
        
        titleLab.text = vipModel.title

        profitTextLab.text = vipModel.profitLabel
        
        if JCWProductStatus(rawValue: vipModel.status) == .prepareSale {
            titleLab.backgroundColor = ColorFromRGBHex_WL(0xc6c6c6)
            titleLab.textColor = ColorFromRGBHex_WL(0x606060)

            statusImg.image = UIImage(named: "advance")
            
        }else if JCWProductStatus(rawValue: vipModel.status) == .saling{
            titleLab.backgroundColor = ColorFromRGBHex_WL(0xdccaa2)
            titleLab.textColor = Color.white //Normal_ThemeColor
            statusImg.image = UIImage(named: "")

        }else{
            titleLab.backgroundColor = ColorFromRGBHex_WL(0xc6c6c6)
            titleLab.textColor = ColorFromRGBHex_WL(0x606060)
            statusImg.image = UIImage(named: "repayment")
        }
        
        if vipModel.cashRateShow == "1"{
            
            profitLab.attributedText = handlerProfit(vipModel.profit, vipModel.cashRateProfit)
        }else{
            
            profitLab.attributedText = handlerProfit(vipModel.profit, vipModel.profitFloat)
        }
        
        
        let money = NSString(money: vipModel.surplusAmount) as String
        surplusAmountLab.adjustsFontSizeToFitWidth = true
        surplusAmountLab.text = "\(vipModel.plstimeLimitLabel ?? "")" + (vipModel.plstimeLimitType == "0" ? "\(vipModel.plstimeLimitValue!)天" : "\(vipModel.plstimeLimitValue!)月") + "  |  " + "\(vipModel.surplusAmountLabel ?? "")" + money
        
        self.tagsView.tagsStr(vipModel.tags)
        _ = tagsView.sd_layout()
            .centerXEqualToView(lineView)?
            .offset(-tagsView.totoalWidth/2)?
            .topSpaceToView(lineView,10)?
            .heightIs(15)
        
    }
    ///处理利率 富文本
    private func handlerProfit(_ str1: String, _ str2: String) -> NSMutableAttributedString {
        
        let str11 = String(format: "%.2f", str1.cGFloat * 100)
        
        let temp = NSMutableAttributedString(string: str11, attributes: [NSFontAttributeName: Font_Auto(18)])
        temp.append(NSAttributedString(string: "%", attributes: [NSFontAttributeName: Font_Auto(15)]))
        if str2.isEmpty {
            return temp
        }else{
            let str22 = String(format: "%.2f", str2.cGFloat * 100)
            temp.append(NSAttributedString(string: "+\(str22)%", attributes: [NSFontAttributeName: Font_Auto(15)]))
            return temp
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

class CustomPageControl: UIPageControl {
    
    
    let activeImage:UIImage = UIImage(named: "home_Solidpoint")!
    let inactiveImage:UIImage = UIImage(named: "home_point")!
    
    override init(frame: CGRect) {
       
//        self.clipsToBounds = false
        super.init(frame: frame)
        self.pageIndicatorTintColor = UIColor.clear
        self.currentPageIndicatorTintColor = UIColor.clear
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func updateDots() {
        var i = 0
        for view in self.subviews {
            if let imageView = self.imageForSubview(view) {
                if i == self.currentPage {
                    imageView.image = self.activeImage
                } else {
                    imageView.image = self.inactiveImage
                }
                i = i + 1
            } else {
                var dotImage = self.inactiveImage
                if i == self.currentPage {
                    dotImage = self.activeImage
                }
                view.clipsToBounds = false
                view.addSubview(UIImageView(image:dotImage))
                i = i + 1
            }
        }
    }
    
    fileprivate func imageForSubview(_ view:UIView) -> UIImageView? {
        var dot:UIImageView?
        
        if let dotImageView = view as? UIImageView {
            dot = dotImageView
        } else {
            for foundView in view.subviews {
                if let imageView = foundView as? UIImageView {
                    dot = imageView
                    break
                }
            }
        }
        
        return dot
    }
}
